package com.card.manager.utils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import com.card.manager.domain.Msa;
import com.card.manager.services.MsaService;


public class DataDictFun {
	
	private final static String NULL = "";
	private DataDictFun(){
		throw new AssertionError("不允许实例化DataDict!");
	}
	private static MsaService service;
	private static MsaService getService(){
		if(service == null){
			WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
			service = wac.getBean(MsaService.class);
		}
		return service;
	}
	private static List<Msa> _listMsaByKindId(String key){
		return getService().selectMsaByKindId(key);
	}
	/**
	 * 根据类型,获得该类型字典的map
	 * @param key
	 * @return
	 */
	public static Map<Long,String> map(String key){
		List<Msa> list = _listMsaByKindId(key);
		
		List<KeyAndValue> result = new ArrayList<KeyAndValue>();
		Map<Long,String> map = new HashMap<Long,String>();
		for(Msa m : list){
			map.put(m.getId(),m.getNamea());
		}
		return map;
	}
	/**
	 * 根据类型,获得该类型字典的List
	 * @param key
	 * @return
	 */
	public static List<KeyAndValue> list(String key){
		List<Msa> list = _listMsaByKindId(key);
		
		List<KeyAndValue> result = new ArrayList<KeyAndValue>();
		for(Msa m : list){
			result.add(new KeyAndValue(m.getId(),m.getNamea()));
		}
		
		return result;
	}
	/**
	 * 根据类别,键,获得值
	 * @param key
	 * @param id
	 * @return
	 */
	public static String val(String key,Long id){
		if(key == null || id == null)
			return NULL;
		String val = map(key).get(id);
		if(StringUtils.isBlank(val))
			val = NULL;
		return val;
	}
	/**
	 * 根据类别获得该类别的字典的json
	 * @param key
	 * @return
	 */
	public static String json(String key){
		JSONObject json = JSONObject.fromObject(map(key));
		return json.toString();
	}
	
	public static class KeyAndValue{
		private long key;
		private String value;
		public KeyAndValue(){}
		
		public KeyAndValue(long key, String value) {
			super();
			this.key = key;
			this.value = value;
		}
		public long getKey() {
			return key;
		}
		public void setKey(long key) {
			this.key = key;
		}
		public String getValue() {
			return value;
		}
		public void setValue(String value) {
			this.value = value;
		}
	}
}
